package net.wanho.util;

import net.wanho.constant.SystemConstant;
import net.wanho.exception.FileException;
import net.wanho.properties.SystemProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    private static final String fileUrl = SystemConstant.STATIC_RESOURCE_PATH;

    private static final String localhost;
    private static final String port;
    private static final String contextPath;

    static {
        try {
            SystemProperties properties = ApplicationContextHolder.getBean(SystemProperties.class);
            localhost = properties.getLocalhost();
            port = properties.getPort();
            contextPath = properties.getServlet().getContextPath();
        } catch (Exception e) {
            logger.error("FileUtil初始化失败", e);
            throw new RuntimeException(e);
        }
    }

    public static String uploadFIle(MultipartFile file){
        String fileName = UUID.randomUUID() + "." + StringUtils.getFilenameExtension(file.getOriginalFilename());
        String path = fileUrl + File.separator + LocalDate.now();
        File uploadFile = new File(path);
        if(!uploadFile.exists()) {
            boolean isSuccess = uploadFile.mkdirs();
            if(!isSuccess) {
                throw new FileException("创建上传文件目录失败");
            }
        }
        try {
            file.transferTo(new File(path + File.separator + fileName));
        } catch (Exception e) {
            throw new FileException("文件上传失败");
        }

        String url = "http://" + localhost + ":" + port + contextPath + "/statics/" + LocalDate.now() + File.separator + fileName;
        System.out.println(url);
        return url;
    }

    public static void deleteFile(String path) {
        String pathUrl = path.substring(path.indexOf("/statics/") + 9);
        File file = new File(fileUrl + pathUrl);
        if(file.exists()) {
            boolean isDelete = file.delete();
            if(!isDelete) {
                throw new FileException("文件删除失败");
            }
        }
    }

    public static void deleteFileBatch(List<String> pathList) {
        ExecutorService executor = ThreadPoolUtil.getExecutor();

        pathList.forEach(path -> executor.submit(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "正在删除文件：" + path);
                deleteFile(path);
            } catch (FileException e) {
                throw new FileException(path + "文件删除失败");
            }
        }));
    }
}
